package com.azure.bigstore.controller;

import com.azure.bigstore.entity.Admin;
import com.azure.bigstore.entity.Token;
import com.azure.bigstore.entity.User;
import com.azure.bigstore.service.AdminService;
import com.azure.bigstore.service.TokenService;
import com.azure.bigstore.service.UserService;
import com.azure.bigstore.utils.CryptUtil;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * Created by Azure on 2018/1/23.
 */
@RestController
@RequestMapping("v1")
public class LoginRegisterController {
    @Autowired
    private UserService userService;

    @Autowired
    private AdminService adminService;

    @Autowired
    private TokenService tokenService;

    @PostMapping("/register")
    public String register(User user){
        User u = userService.findByUsername(user.getUsername());
        if(u != null){
            return "-1";//-1:已存在 -2:传入的user为空    1：保存成功  0：保存失败
        }else{
            user.setCreatedate(new Date());
            return userService.saveUser(user);
        }
    }

    @PostMapping("/login")
    public String login(String email, String password){
        User u = userService.findByUsernameAndPassword(email, password);
        if(u == null){
            return "0";// 0:用户名或密码错误
        }else{
            long time = new Date().getTime()+1800000;//延长30分钟
            System.out.println("now:"+new Date()+"  time"+new Date(time));
            Token token = tokenService.findByUID(u.getID());
            //未查询到token
            if(token == null){
                token = new Token(u.getID(), CryptUtil.MD5("user"+time+u.getID()),new Date(time));
                tokenService.saveToken(token);
            }else{
                token.setValidityTime(new Date(time));
                tokenService.saveToken(token);
            }

            return token.getToken();
        }
    }
    @PostMapping("/adminlogin")
    public String adminLogin(String email, String password){
        Admin admin = adminService.findByUsernameAndPassword(email, password);
        //用户名和密码错误
        if(admin == null){
            return "0";// 0:用户名或密码错误
        }else{
            long time = new Date().getTime()+1800000;//延长30分钟
            System.out.println("now:"+new Date()+"  time"+new Date(time));
            Token token = tokenService.findByUID(admin.getID());
            //未查询到token
            if(token == null){
                token = new Token(admin.getID(), CryptUtil.MD5("admin"+time+admin.getID()),new Date(time));
                tokenService.saveToken(token);
            }else{
                token.setValidityTime(new Date(time));
                tokenService.saveToken(token);
            }

            return token.getToken();
        }
    }
}
